﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;

namespace UNSWThink
{
   /// <summary>
   /// Windows form used to accept input relating to user login from the user.
   /// </summary>
   public partial class LoginForm : Form
   {
      private string resultMessage;
      private DBConnection dbConn;

      /// <summary>
      /// Default constructor
      /// </summary>
      /// <param name="dbConnection">
      /// DBConnection used to peform database queries required for user login
      /// </param>
      public LoginForm(DBConnection dbConnection)
      {
         InitializeComponent();

         resultMessage = "";
         dbConn = dbConnection;
      }

      /*
       * WINDOWS FORM EVENTS
       */

      private void Login_Load(object sender, EventArgs e)
      {
         usernameTextBox.Focus();
      }

      private void Form1_FormClosing(object sender, FormClosingEventArgs e)
      {

      }

      /*
       * CONTROL EVENTS
       */

      private void loginButton_Click(object sender, EventArgs e)
      {
         int id = 0;
         string passwordHash = HelperMethods.GetMd5Hash(passwordTextBox.Text);

         bool loginSuccessful = dbConn.AttemptInstuctorLogin(usernameTextBox.Text, passwordHash, ref id);

         if (loginSuccessful)
         {
            //if (this.ParentForm.GetType() == typeof(WinStart))
            if (this.Owner.GetType() == typeof(StartForm))
            {
               StartForm mainForm = (StartForm)this.Owner;
               mainForm.LoggedIn = loginSuccessful;
               mainForm.InstructorID = id;
            }

            this.Close();
         }
         else
         {
            MessageBox.Show("Unsuccessful login. Username and/or password is incorrect.", "Unsuccessful login", MessageBoxButtons.OK, MessageBoxIcon.Hand);
         }
      }

      private void exitButton_Click(object sender, EventArgs e)
      {
         this.Close();
      }

      private void usernameTextBox_TextChanged(object sender, EventArgs e)
      {
         if (usernameTextBox.Text != "")
         {
            passwordTextBox.Enabled = true;
         }
         else
         {
            passwordTextBox.Enabled = false;
         }
      }

      /*
       * PROPERTIES
       */

      /// <summary>
      /// Gets the result message of the most recent action
      /// </summary>
      public string ResultMessage
      {
         get
         {
            return resultMessage;
         }
      }
   }
}
